import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import Cookies from 'js-cookie'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: Home
  },
  {
    path: '/class',
    name: '分类页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Class')
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true
    },
    component: () => import('@views/Cart')
  },
  {
    path: '/user',
    name: '个人中心',
    meta: {
      needLogin: true
    },
    component: () => import('@views/User')
  },
  {
    path: '/serch/:name',
    name: '搜索页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Serch/')
  },
  {
    path: '/details',
    name: '详情页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Details/')
  },
  {
    path: '/login',
    name: '登录页',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Login/')
  },
  {
    path: '/regist',
    name: '注册',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Regist/')
  },
  {
    path: '/homeSearch',
    name: '首页搜索',
    meta: {
      needLogin: false
    },
    component: () => import('@views/HomeSearch/')
  },
  {
    path: '/searchItems',
    name: '搜索详情',
    meta: {
      needLogin: false
    },
    component: () => import('@views/SearchItems/')
  },
  {
    path: '/order',
    name: '支付订单页',
    meta: {
      needLogin: true
    },
    component: () => import('@views/Order')
  },
  {
    path: '/modify',
    name: '修改地址页',
    meta: {
      needLogin: true
    },
    component: () => import('@views/Modify')
  },
  {
    path: '/address',
    name: '增加地址页',
    meta: {
      needLogin: true
    },
    component: () => import('@views/Address')
  },
  {
    path: '/addressList',
    name: '地址列表页',
    meta: {
      needLogin: true
    },
    component: () => import('@views/AddressList')
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (!to.meta.needLogin) {
    next()
  } else {
    const token = Cookies.get('token')
    if (to.path === '/login') {
      next()
    } else {
      if (token) {
        next()
      } else {
        next({
          path: '/login',
          query: {
            form: to.path
          }
        })
      }
    }
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
export default router
